"use client"

import { useEffect } from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@/components/ui/select"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { Access, Track } from "@/types/admin"
import { useAdminStore } from "@/lib/store"

const formSchema = z.object({
  name: z.string().min(1, "门禁名称不能为空"),
  location: z.string().min(1, "位置不能为空"),
  type: z.string().min(1, "请选择门禁类型"),
  status: z.string().min(1, "请选择门禁状态"),
  lastMaintenance: z.string().optional(),
  trackId: z.string().optional(),
})

type FormValues = z.infer<typeof formSchema>

interface AccessDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  access?: Access
  onSave: (data: Omit<Access, 'id'>) => void
}

export function AccessDialog({
  open,
  onOpenChange,
  access,
  onSave,
}: AccessDialogProps) {
  const isEditing = !!access
  const { tracks } = useAdminStore()

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: access?.name || "",
      location: access?.location || "",
      type: access?.type || "",
      status: access?.status || "正常",
      lastMaintenance: access?.lastMaintenance || new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      }).replace(/\//g, '-'),
      trackId: access?.track?.id || "",
    },
  })

  useEffect(() => {
    if (open) {
      if (access) {
        form.reset({
          name: access.name,
          location: access.location,
          type: access.type,
          status: access.status,
          lastMaintenance: access.lastMaintenance,
          trackId: access.track?.id || "",
        })
      } else {
        form.reset({
          name: "",
          location: "",
          type: "",
          status: "正常",
          lastMaintenance: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          }).replace(/\//g, '-'),
          trackId: "",
        })
      }
    }
  }, [open, access, form])

  const onSubmit = (values: FormValues) => {
    // 查找选中的股道对象
    const selectedTrack = values.trackId ? tracks.find(track => track.id === values.trackId) : undefined
    
    // 提交表单数据，包括关联的股道
    onSave({
      name: values.name,
      location: values.location,
      type: values.type,
      status: values.status,
      lastMaintenance: values.lastMaintenance || "",
      track: selectedTrack,
    })
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[550px]">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑门禁" : "新增门禁"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改门禁信息，点击保存确认更改。"
              : "添加新门禁，设置门禁名称、位置和类型。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>门禁名称</FormLabel>
                  <FormControl>
                    <Input placeholder="如：主控室门禁" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="location"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>位置</FormLabel>
                  <FormControl>
                    <Input placeholder="如：丁堰车辆段主控室" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>门禁类型</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择门禁类型" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="刷卡门禁">刷卡门禁</SelectItem>
                        <SelectItem value="人脸识别">人脸识别</SelectItem>
                        <SelectItem value="指纹识别">指纹识别</SelectItem>
                        <SelectItem value="双重验证">双重验证</SelectItem>
                        <SelectItem value="其他">其他</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>状态</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择门禁状态" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="正常">正常</SelectItem>
                        <SelectItem value="维护中">维护中</SelectItem>
                        <SelectItem value="故障">故障</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="lastMaintenance"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>最近维护时间</FormLabel>
                  <FormControl>
                    <Input type="text" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="trackId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>关联股道</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    value={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="选择关联股道" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="">不关联股道</SelectItem>
                      {tracks.map((track) => (
                        <SelectItem key={track.id} value={track.id}>
                          {track.name} ({track.code})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="submit">
                {isEditing ? "保存" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
